import useTable from "../../../framework/common/lifecycle/useTable"
import request from "../../../framework/common/utils/request";
import { Modal, Select, Form, Input, Table, Tag, Button, message } from "antd";
import eventBus, { useSubscribe } from "../../../framework/common/eventBus";
import { useRef, useState } from "react";
import { useUpdate } from "ahooks";
const { Option } = Select;

export default function (){
    //生成table组件
  const [form] = Form.useForm();
  const { tableProps, search } = useTable(
    (
      {
        current = 1, // 设定初始在第1页
        pageSize, // 初始每页默认10条数据
        // sorter,
      },
      formData
    ) => {
      return request({
        url: "/platform/application/get-list",
        method: "post",
        data: {
            pageIndex: current,
            pageSize: pageSize,
            ...formData
        },
      }).then(function (response) {
        if(response?.code === 1){
            let list = response?.data?.list || [];
            list.forEach((item, index) => {
              item.index = index + 1 + (current - 1) * 10;//设置序号
            });
            return {
              total: response.data.total,
              list: list,
            };
        }
      });
    },
    {
      form,
      defaultPageSize: 10
    }
  );
  const { submit } = search;

  useSubscribe("updateTable.update", ()=>{
    submit();
  })

  //生成table列信息
  let columns = [
        {
            title: "序号",
            dataIndex: "index",
            width: 70,
            align:"center"
        },
        {
            title: "应用名称",
            dataIndex: "Name",
            width: 150,
        },
        {
            title: "应用编码",
            dataIndex: "Code",
            width: 150,
        },
        {
            title: "版本号",
            dataIndex: "Version",
            width: 150,
        },
        {
            title: "新增时间",
            dataIndex: "CreationTime"
        },
        {
            title: "模板包来源",
            dataIndex: "Source",
            width: 150,
            render:(Source)=>{
                return <>
                    {
                        Source == 1 ? "模板库" : "应用市场"
                    }
                </>
            }
        },
        {
            title: "模板包当前版本",
            dataIndex: "CurrentTemplateVersion",
            render:(CurrentTemplateVersion)=>{
                return CurrentTemplateVersion ? CurrentTemplateVersion : "-";
            }
        },
        {
            title: "模板包更新时间",
            dataIndex: "LastTemplateUpdateTime",
            render:(LastTemplateUpdateTime)=>{
                return LastTemplateUpdateTime ? LastTemplateUpdateTime : "-";
            }
        },
        {
          title: '操作',
          dataIndex: '',
          key: 'x',
          width: 140,
          render: (rowData) => {
            return <>
                <Button type="link"
                    onClick={()=>{
                        editApp({
                            rowData: rowData,//编辑时，传入当前行数据
                            modalTitle: "编辑应用",
                            type: "edit"
                        });//编辑
                    }}
                >编辑</Button>
                <UpdateBtn rowData={rowData}></UpdateBtn>
            </>
          },
        },
  ];

  //设置输入框placeholder
  return <>
    <div className="pt-3 px-3">
        <Form 
            form={form}
            layout={"inline"}
            initialValues={
                {
                    Name:"",
                    Code: ""
                }
            }
        >
            <Form.Item  name="Name" >
                <Input className="mr-3" autoComplete="off" placeholder="应用名称" style={{ width: 290}} />
            </Form.Item>
            <Form.Item  name="Code">
                <Input  autoComplete="off" placeholder="应用编码" style={{ width: 290}} />
            </Form.Item>
            <Form.Item>
                <Button type="primary"
                    className="mr-3"
                    htmlType="submit"
                    onClick={submit}
                >筛选</Button>
                <Button onClick={()=>{
                    form.resetFields();
                    submit();
                }}>重置</Button>
            </Form.Item>
        {/* onSearch={submit} */}
        </Form>
    </div>
    <div className="overflow-hidden pb-2 pt-3 px-3 leading-8">
        <span className="text-base">应用列表</span>
        <Button 
            type="primary"
            className="float-right"
            onClick={()=>{
                editApp({
                    modalTitle: "新增应用",
                    type: "add"
                });
            }}
        >新增</Button>
    </div>
    <Table
      className="table-content-full"
      columns={columns}
      scroll={{ y: 2000 }} 
      rowKey={"Code"}
      {...tableProps}
    />

    <AppModal></AppModal>
  </>
}

//同步按钮
function UpdateBtn({
    rowData
}){
    let btnRef = useRef(false);
    let update = useUpdate();
    return <Button type="link"
                loading={btnRef.current}
                onClick={()=>{
                    //1.按钮增加loading状态
                    btnRef.current = true;
                    update();
                    return request({
                        url: "/platform/application/app-sync",//同步接口
                        method: "post",
                        data: rowData,
                      }).then(
                        function (response) {
                            //2.按钮取消loading状态
                            btnRef.current = false;
                            update();

                            if(response?.code === 1){//请求成功
                                message.success('同步成功');
                                // 3 重新加载列表
                                eventBus.publish("updateTable.update");
                            }
                        },
                        function(res){//请求挂掉
                            
                            //2.按钮取消loading状态
                            btnRef.current = false;
                            update();

                        }
                    );
                }}
            >同步</Button>
}

//应用管理编辑/新增弹出框
function AppModal(){
    const [form] = Form.useForm();
    const [data, setData] = useState({
        type: "add",//模式 add：新增 edit：编辑
        visible: false,//modal显示状态
        confirmLoading: false,//确定按钮loading状态
        modalTitle: "新增应用"
    });
    useSubscribe("setAppModalData.update", (newData)=>{
        setData({
            ...data,
            ...newData
        });
        if(newData.rowData){//如果传入了表单数据，则进入编辑模式
            form.setFieldsValue(newData.rowData);
        }
    }, [data]);//注册更新当前组件的事件

    return <>
        <Modal 
            width={600}
            title={data.modalTitle} 
            visible={data.visible} 
            onOk={()=>{
                //保存事件
                form.validateFields().then(function(res){
                    if(data.type === "edit"){
                        res.Id = data?.rowData?.Id;//编辑模式把对应的Id给到后端
                    }
                    //验证成功后，提交表单
                    submitApp({
                        formData: res,
                        type: data.type
                    });
                });
            }} 
            onCancel={()=>{
                form.resetFields();//重置表单数据
                setData({
                    visible: false
                })
            }}
            confirmLoading={data.confirmLoading}
            cancelText="取消"
            okText="保存"
            centered={true}
        >
            <div className="pl-3">
                <Form 
                    labelAlign="left"
                    labelCol={{
                        span: 6,
                    }}
                    colon={false}
                    form={form}
                >
                    <Form.Item 
                        label="应用名称"
                        name="Name"
                        rules={[
                            {
                                required: true,
                                message: '请输入应用名称',
                            },
                        ]}              
                    >
                        <Input className="mr-3" autoComplete="off" placeholder="请输入" />
                    </Form.Item>
                    <Form.Item 
                        label="应用编码"
                        name="Code"
                        rules={[
                            {
                                required: true,
                                message: '请输入应用编码',
                            }
                        ]}              
                    >
                        <Input  autoComplete="off" placeholder="请输入" />
                    </Form.Item>
                    <Form.Item
                        label="版本号"
                        name="Version"
                        rules={[
                            {
                                required: true,
                                message: '请输入版本号',
                            },
                            // {
                            //     pattern: /^\d+(\.\d+)*$/g,
                            //     message: '只能包含数字和小数点.，且需要数字开头和结尾',
                            // }
                        ]} 
                    >
                        <Input  autoComplete="off" placeholder="请输入" />
                    </Form.Item>
                    <Form.Item
                        label="模板资源包来源"
                        name="Source"
                        rules={[
                            {
                                required: true,
                                message: '请选择模板资源包来源',
                            },
                        ]} 
                    >
                        <Select
                            placeholder="请选择"
                        >
                            <Option key="1" value={1}>模板库</Option>
                            <Option key="2" value={2}>应用市场</Option>
                        </Select>
                    </Form.Item>
                </Form>
            </div>
        </Modal>
    </>
}

//新增/编辑应用
function editApp({
    rowData = null,//需要编辑的数据
    modalTitle,
    type = "add"//操作类型 add || edit
}){
    eventBus.publish("setAppModalData.update", {
        visible: true,
        rowData: rowData,//新增重置表单数据
        modalTitle: modalTitle,
        type: type
    })//显示编辑弹框
}

//提交应用编辑
function submitApp({
    formData,
    type = "add"//操作类型 add || edit
}){
    eventBus.publish("setAppModalData.update", {
        confirmLoading: true
    })

    let url = "/platform/application/create";//新增
    if(type === "edit"){
        url = "/platform/application/update";//编辑
    }

    return request({
        url: url,
        method: "post",
        data: formData,
      }).then(
        function (response) {
            if(response?.code === 1){//请求成功
                // 1 提示成功
                message.success('保存成功');
                //message.error('保存失败');
                // 2 关闭弹框
                eventBus.publish("setAppModalData.update", {
                    visible: false,
                    confirmLoading: false
                });
                // 3 重新加载列表
                eventBus.publish("updateTable.update", );
            }else{//请求失败
                //  取消弹窗loading效果
                eventBus.publish("setAppModalData.update", {
                    // visible: true,
                    confirmLoading: false
                });
            }
        },
        function(res){//请求挂掉
            //  取消弹窗loading效果
            eventBus.publish("setAppModalData.update", {
                visible: true,
                confirmLoading: false
            });
        }
    );
}